#include <hpdf.h>
#include <iostream>
#include <string>
#include <vector>
#include <cstring>

void error_handler(HPDF_STATUS error_no, HPDF_STATUS detail_no, void* user_data) {
    printf("ERROR: error_no=%04X, detail_no=%d\n", (unsigned int)error_no, (int)detail_no);
}

int main() {
    HPDF_Doc pdf = nullptr;
    HPDF_Page page = nullptr;
    HPDF_Font font = nullptr;
    
    try {
        pdf = HPDF_New(error_handler, NULL);
        if (!pdf) {
            throw std::runtime_error("无法创建PDF文档");
        }

        HPDF_UseJPEncodings(pdf);
        HPDF_UseKREncodings(pdf);
        HPDF_UseCNSEncodings(pdf);
        HPDF_UseCNTEncodings(pdf);

        const char* font_path = "/usr/share/fonts/chinese/simsun.ttf";
        const char* font_name = HPDF_LoadTTFontFromFile(pdf, font_path, true);
        
        if (!font_name) {
            throw std::runtime_error("无法加载字体文件");
        }

        font = HPDF_GetFont(pdf, font_name, "GB-EUC-H");
        if (!font) {
            throw std::runtime_error("无法创建字体对象");
        }

        const int charsPerLine = 15;
        const int charsPerPage = 300;
        const float fontSize = 12;
        const float lineHeight = 20;
        const float marginLeft = 50;
        const float marginTop = 50;

        std::vector<unsigned short> characters;
        for (unsigned short c = 0x4E00; c <= 0x9FFF; c++) {
            characters.push_back(c);
        }

        int currentChar = 0;
        int pageCount = 0;

        while (currentChar < characters.size()) {
            page = HPDF_AddPage(pdf);
            HPDF_Page_SetSize(page, HPDF_PAGE_SIZE_A4, HPDF_PAGE_PORTRAIT);
            HPDF_Page_SetFontAndSize(page, font, fontSize);
            pageCount++;

            for (int i = 0; i < charsPerPage && currentChar < characters.size(); i++) {
                int row = i / charsPerLine;
                int col = i % charsPerLine;

                unsigned short unicode = characters[currentChar];
                char buf[3] = {0};
                
                if (unicode >= 0x4E00 && unicode <= 0x9FFF) {
                    buf[0] = ((unicode - 0x4E00) / 94) + 0xB0;
                    buf[1] = ((unicode - 0x4E00) % 94) + 0xA1;
                }

                float x = marginLeft + col * fontSize * 1.5f;
                float y = HPDF_Page_GetHeight(page) - marginTop - row * lineHeight;

                HPDF_Page_BeginText(page);
                HPDF_Page_MoveTextPos(page, x, y);
                HPDF_Page_ShowText(page, buf);
                HPDF_Page_EndText(page);

                currentChar++;
            }
        }

        HPDF_SaveToFile(pdf, "chinese_characters.pdf");
        HPDF_Free(pdf);
        
    } catch (const std::exception& e) {
        std::cerr << "错误：" << e.what() << std::endl;
        if (pdf) {
            HPDF_Free(pdf);
        }
        return 1;
    }

    return 0;
}
